<template>
  <view class="address-picker" v-if="visible">
    <view class="picker-mask" @tap="cancel"></view>
    <view class="popup">
      <view class="picker-btn">
        <view class="left" @click="cancel">取消</view>
        <view class="right" @click="confirm">确定</view>
      </view>
      <picker-view
        :indicator-style="indicatorStyle"
        :value="valueArr"
        @change="bindChange"
      >
        <picker-view-column>
          <view
            class="item"
            v-for="(item, index) in province[0]"
            :key="index"
            >{{ item.name }}</view
          >
        </picker-view-column>
        <picker-view-column v-if="province[1]">
          <view
            class="item"
            v-for="(item, index) in province[1]"
            :key="index"
            >{{ item.name }}</view
          >
        </picker-view-column>
        <picker-view-column v-if="province[2]">
          <view
            class="item"
            v-for="(item, index) in province[2]"
            :key="index"
            >{{ item.name }}</view
          >
        </picker-view-column>
      </picker-view>
    </view>
  </view>
</template>
<script>
import provinces from "./provinces.json";
import cities from "./cities.json";
import areas from "./areas.json";

export default {
  props: {
    value: {
      type: String,
      default: "",
    },

    twoStage: {
      type: Boolean,
      default: false,
    },
  },
  name: "ZlAddress",
  data() {
    return {
      visible: false,
      indicatorStyle: `height: ${Math.round(
        uni.getSystemInfoSync().screenWidth / (750 / 100)
      )}px;`,
      valueArr: [0, 0, 0], // 用于判断当前滑动的是哪一列
      province: [provinces], // 数据列表
    };
  },

  methods: {
    setIndex(i, value) {
      this.$set(this.valueArr, i, value);
    },
    initLoadArea() {
      this.loadCity(provinces[0].code);
    },
    loadCity(code) {
      if (!code) return;
      let children = cities.filter((v) => v.provinceCode == code);
      this.$set(this.province, 1, children);

      if (!this.twoStage && children.length > 0) {
        this.loadArea(children[0].code);
        this.valueArr[1] = 0;
        this.valueArr[2] = 0;
      }
    },
    loadArea(code) {
      if (!code) return;
      let areas_filtered = areas.filter((v) => v.cityCode == code);
      this.$set(this.province, 2, areas_filtered);
      this.valueArr[2] = 0;
    },

    bindChange(e) {
      const val = e.detail.value;
      try {
        // 检查省份是否存在
        const province = this.province[0]?.[val[0]];
        if (!province) return;

        if (this.valueArr[0] !== val[0]) {
          let code = province.code;
          this.loadCity(code);
        } else if (this.valueArr[1] !== val[1]) {
          // 检查城市是否存在
          const city = this.province[1]?.[val[1]];
          if (!city) return;
          
          if (!this.twoStage) {
            let code = city.code;
            this.loadArea(code);
          }
        }
        this.valueArr = val;
      } catch (error) {
        console.error('选择器变更错误:', error);
      }
    },

    confirm() {
      let addressDetail = "";
      try {
        const province = this.province[0]?.[this.valueArr[0]];
        const city = this.province[1]?.[this.valueArr[1]];
        const district = this.province[2]?.[this.valueArr[2]];
        
        if (!province?.name || !city?.name) {
          uni.showToast({
            title: '请选择完整的地址',
            icon: 'none'
          });
          return;
        }

        if (!this.twoStage) {
          if (!district?.name) {
            uni.showToast({
              title: '请选择区/县',
              icon: 'none'
            });
            return;
          }
          addressDetail = `${province.name} ${city.name} ${district.name}`;
        } else {
          addressDetail = `${province.name} ${city.name}`;
        }

        this.$emit("confirm", addressDetail);
        this.visible = false;
      } catch (error) {
        console.error('地址选择错误:', error);
        uni.showToast({
          title: '地址选择有误，请重新选择',
          icon: 'none'
        });
      }
    },

    open() {
      this.visible = true;
      // 重置选择器状态
      this.valueArr = [0, 0, 0];
      this.province = [provinces];
      
      if (!this.value) {
        this.initLoadArea();
      } else {
        this.$nextTick(() => {
          this.echoLoad();
        });
      }
    },

    echoLoad() {
      try {
        let val = this.value.split("-");
        if (val.length < 2) return;

        let sheng = provinces.findIndex((v) => v.name == val[0]);
        if (sheng === -1) return;
        this.setIndex(0, sheng);

        let children = cities.filter((v) => v.provinceCode == provinces[sheng].code);
        this.$set(this.province, 1, children);
        
        let shi = children.findIndex((v) => v.name == val[1]);
        if (shi === -1) return;
        this.setIndex(1, shi);

        if (!this.twoStage && val[2]) {
          let children2 = areas.filter((v) => v.cityCode == children[shi].code);
          this.$set(this.province, 2, children2);
          let qu = children2.findIndex((v) => v.name == val[2]);
          if (qu !== -1) {
            this.setIndex(2, qu);
          }
        }
      } catch (error) {
        console.error('地址回显错误:', error);
        this.valueArr = [0, 0, 0];
        this.initLoadArea();
      }
    },
    cancel() {
      this.visible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.address-picker {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 999;
}

.picker-mask {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
}

.popup {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: fit-content;
  width: 100%;
  background: #fff;
  animation: slideUp 0.3s ease;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.picker-btn {
  display: flex;
  height: 100rpx;
  width: 100%;
  line-height: 100rpx;
  background: #fff;
  font-size: 34rpx;
  z-index: 1;
  border-bottom: 1rpx solid #f8f8f8;

  .left {
    flex: 1;
    color: #0076ff;
    padding-left: 40rpx;
    box-sizing: border-box;
  }

  .right {
    flex: 1;
    text-align: right;
    padding-right: 40rpx;
    color: #fe4533;
    box-sizing: border-box;
  }
}

picker-view {
  width: 100%;
  height: 500rpx;
  display: relative;
}
.item {
  line-height: 100rpx;
  text-align: center;
}
</style>
